function Urp() {
};

Urp.prototype = {
	"alert": urpAlert,
	"confirm": urpConfirm,
	"pagebar": pagination,
	"trhighlight": trhighlight,
	"fixedheader": fixedheader,
	"translationWeek": translationWeek,
	"mergeSession": mergeSession,
	"arrayIntersection": arrayIntersection,
	"keyDo": keyDo,
	"addModelHt": addModelHt,
	"intSwitchXnxq": intSwitchXnxq,
	"showPlaintext": showPlaintext
};

function showPlaintext(ciphertext, obj) {
	var index;
    $.ajax({
        url: "/admin/common/showPlaintext",
        cache: false,
        type: "post",
        data: "ciphertext=" + ciphertext,
        dataType: "json",
        beforeSend: function () {
            index = layer.load(0, {
                shade: [0.2, "#000"] //0.1透明度的白色背景
            });
        },
        complete: function () {
            layer.close(index);
        },
        success: function (d) {
            if(d.result == "err") {
            	urp.alert("查询明文数据失败！");
            } else {
            	$(obj).html(d.result);
            	$(obj).attr("onclick", "");
            	$(obj).attr("style", "");
            }
        },
        error: function (xhr) {
            urp.alert("错误代码[" + xhr.readyState + "-" + xhr.status + "]:获取数据失败！");
        }
    });
}
function urpAlert(msg, callback) {
	layer.msg(msg);
	if (typeof callback === 'function') {
		setTimeout(callback, 1000);
	}
};

function urpConfirm(msg, callback) {
	layer.confirm(
		msg,
		{btn: ['确定', '取消'], closeBtn: 0, title: "提示信息"},
		function () {
			if (typeof callback === 'function') {
				layer.closeAll('dialog');
				callback(true);
			}
		},
		function () {
			if (typeof callback === 'function') {
				callback(false);
			}
		}
	);
};

/**
 * 页面使用：urp.trhighlight("pyfaTable");
 * 点击td,tr高亮函数
 * @param tableId table的id
 * @param more 给参数则可以可多行标记，不给值则单选
 */
function trhighlight(tableId, more) {
	if (more != undefined && more != null) {
		$("#" + tableId + " td").click(function () {
			$(this).closest('tr').addClass('highlight');
		});
	} else {
		$("#" + tableId + " td").click(function () {
			$(".highlight").removeClass("highlight");
			$(this).closest('tr').addClass('highlight');
		});
	}
}


/**
 * 页面使用：urp.fixedheader("pyfaDivTable");
 * 固定表头的方法
 * @param tableDivId table外层的div的id
 * @param divHeight div的高度，默认值是450px 暂不可用
 */
function fixedheader(tableDivId, divHeight) {
	var h = (divHeight == undefined || divHeight == null) ? '\'450\'' : divHeight;

	if ($("#" + tableDivId).size() > 0) {
		$("#" + tableDivId).addClass('table-cont');
		$("#" + tableDivId + " table").css({"margin-top": "-2px", "display": "table", "border-collapse": "separate"});
		//$("#"+tableDivId).css({"max-height":h,"overflow":"auto"});
		var tableCont = document.querySelector('#' + tableDivId);

		function scrollHandle(e) {
			var scrollTop = this.scrollTop - 1;
			this.querySelector('thead').style.transform = 'translateY(' + scrollTop + 'px)';
		}

		tableCont.addEventListener('scroll', scrollHandle);
	}

}

/*!
 * 翻译星期，小写数字翻译成大写
 * 1 --> 一
 */
function translationWeek(week) {
	if (week == null || week == "") {
		return "";
	}
	var weeks = new Array("", "一", "二", "三", "四", "五", "六", "日");
	return weeks[week];

}

/*!
 * 合并节次和持续节次
 * 3 2 --> 3-4节
 */
function mergeSession(session, num) {
	var sessionName;
	sessionName = session;
	if (num != null && Number(num) > 1) {
		sessionName += "-" + (Number(session) + Number(num) - 1) + "节";
	}
	return sessionName;
}

/*!
 *
 * 根据id将元素转换为图片，并打印
 * id 要打印内容区域的id
 * callback 打印之后的回调函数，用于恢复页面
 */
function html2jspprint(id, callback) {

	var shareContent = document.querySelector("#" + id);
	var width = shareContent.offsetWidth;
	var height = shareContent.offsetHeight;
	var canvas = document.createElement("canvas");
	var scale = 2;

	canvas.width = width * scale;
	canvas.height = height * scale;
	canvas.getContext("2d").scale(scale, scale);
	var opts = {
		scale: scale,
		canvas: canvas,
		logging: true,
		width: width,
		height: height
	};

	html2canvas(shareContent, opts).then(function (canvas) {

		canvas.id = "mycanvas";
		var dataUrl = canvas.toDataURL();
		var newImg = document.createElement("img");
		newImg.src = dataUrl;
		var dvHt = $("#page-content-template").html();
		$("#page-content-template").html('<img style="width: 100%;" src="' + newImg.src + '" />');

		newImg.onload = function () {
			window.print();
			$("#page-content-template").html(dvHt);
			callback.call(this);
		};
	});
}
/*
 *
 * 两个数组取交集
 */
function arrayIntersection(a, b) {
	var ai = 0, bi = 0;
	var result = new Array();
	while (ai < a.length && bi < b.length) {
		if (a[ai] < b[bi]) {
			ai++;
		}
		else if (a[ai] > b[bi]) {
			bi++;
		}
		else /* they're equal */
		{
			result.push(a[ai]);
			ai++;
			bi++;
		}
	}
	return result;
}


/**
 * ztree 树上的查询
 * @param inputid 输入框的id
 * @param treeid  树的id
 * @param labelid 用于显示所有结果的labelid
 * @returns {string}
 */
function keyDo(inputid, treeid, labelid) {
	var lastValue = "", nodeList = [];
	var key = $("#" + inputid);
	key.on("focus", focusKey)
		.on("blur", blurKey)
		.on("keyup", doSearch);

	function callNumber(nodes) {
		var zTree = $.fn.zTree.getZTreeObj(treeid);
		if (nodes.length) {
			zTree.selectNode(nodes[0], false);
			document.getElementById(inputid).focus();
			clickCount = 0; //防止重新输入的搜索信息的时候，没有清空上一次记录
			var num = clickCount + 1;
			document.getElementById(labelid).innerHTML = "[" + num + "/" + nodes.length + "]";
		} else if (nodes.length == 0) {
			document.getElementById(labelid).innerHTML = "[0/0]";
			zTree.cancelSelectedNode(); //取消焦点
		}
		if (document.getElementById(inputid).value == "") {
			document.getElementById(labelid).innerHTML = "";
			zTree.cancelSelectedNode();
		}
	}

	function doSearch(event) {
		if (event.keyCode == 13) {
			searchNode(event);
			return false;
		}
	}

	function focusKey(e) {
		if (key.hasClass("empty")) {
			key.removeClass("empty");
		}
	}

	function blurKey(e) {
		if (key.get(0).value === "") {
			key.addClass("empty");
		}
		searchNode(event);
	}

	//搜索节点
	function searchNode(e) {
		var zTree = $.fn.zTree.getZTreeObj(treeid);
		var value = $.trim(key.get(0).value);
		var keyType = "title";
		if (key.hasClass("empty")) {
			value = "";
		}
		if (lastValue === value) return;
		lastValue = value;
		var allNodes = zTree.transformToArray(zTree.getNodes());
		updateNodes(zTree, allNodes, false);
		if (value === "") {
			document.getElementById(labelid).innerHTML = "";
			return;
		}
		;
		nodeList = zTree.getNodesByParamFuzzy(keyType, value); //调用ztree的模糊查询功能，得到符合条件的节点
		updateNodes(zTree, nodeList, true);
		callNumber(nodeList);
	}

	//高亮显示被搜索到的节点
	function updateNodes(treeObj, nodes, highlight) {
		for (var i = 0, l = nodes.length; i < l; i++) {
			nodes[i].highlight = highlight; //高亮显示搜索到的节点(highlight是自己设置的一个属性)
			if (highlight) {
				treeObj.expandNode(nodes[i].getParentNode(), true);
			}
			treeObj.updateNode(nodes[i]); //更新节点数据，主要用于该节点显示属性的更新
		}
	}

	//点击向上按钮时，将焦点移向上一条数据
	$("#" + inputid).closest('div').find("i.clickUp").unbind("click").click(function () {
		var zTree = $.fn.zTree.getZTreeObj(treeid);
		var total = nodeList.length - 1;
		if (nodeList.length == 0) {
			urp.alert("没有搜索结果！");
			return;
		} else if (clickCount == 0) {
			urp.alert("您已位于第一条记录上！");
			return;
		} else {
			clickCount--;
			zTree.selectNode(nodeList[clickCount], false);
		}
		document.getElementById(inputid).focus();
		num = clickCount + 1;
		document.getElementById(labelid).innerHTML = "[" + num + "/" + nodeList.length + "]";
	});
	//点击向下按钮时，将焦点移向下一条数据
	$("#" + inputid).closest('div').find("i.clickDown").unbind("click").click(function () {
		var zTree = $.fn.zTree.getZTreeObj(treeid);
		var total = nodeList.length - 1;
		if (nodeList.length == 0) {
			urp.alert("没有搜索结果！");
			return;
		} else if (total == clickCount) {
			urp.alert("您已位于最后一条记录上！")
			return;
		} else {
			clickCount++;
			zTree.selectNode(nodeList[clickCount], false)
		}
		document.getElementById(inputid).focus();
		num = clickCount + 1;
		document.getElementById(labelid).innerHTML = "[" + num + "/" + nodeList.length + "]";
	})
}

//添加一个用于显示模态框的代码
function addModelHt(width, id) {
	var modal = '<div class="modal fade" id="' + (id == undefined ? 'modal-' + new Date().getTime() : id) + '" data-backdrop="static" data-keyboard="false">\
                    <div class="modal-dialog" style="width: ' + (width == undefined ? '80%' : width) + ';" >\
                        <div class="modal-content">\
                            <div class="center">\
                                <img src="/img/icon/pageloading.gif" style="width:28px;height:28px;"></img>\
                            </div>\
                        </div>\
                    </div>\
                </div>';
	var modal = $(modal).appendTo('body');
	return modal;
}

function intSwitchXnxq(xnxqId, searchId) {
	$("#" + xnxqId).after("<div style='display: inline-block; vertical-align: top; margin-top: -1px;'>\
							<button type='button' class='btn btn-xs btn-info' style='vertical-align: top; display: block;\
						height: 12px; padding: 0 5px; font-size: 13px; border: 0; margin-top: 1px;'\
								onclick='switchXnxq(\"" + xnxqId + "\", \"" + searchId + "\", -1);'>\
								<i class='fa fa-chevron-up' style='vertical-align: top;'></i>\
							</button>\
							<button type='button' class='btn btn-xs btn-info' style='vertical-align: top; display: block;\
						height: 12px; padding: 0 5px; font-size: 13px; border: 0; margin-top: 1px;'\
								onclick='switchXnxq(\"" + xnxqId + "\", \"" + searchId + "\",1);'>\
								<i class='fa fa-chevron-down' style='vertical-align: top;'></i>\
							</button></div>");
}

function switchXnxq(xnxqId, searchId, turn) {
	var option = $("#" + xnxqId + " option");
	if (option.length == 0) {
		urp.alert("无学年学期下拉项！");
		return;
	}

	var index = $("#" + xnxqId + " option[value='" + $("#" + xnxqId).val() + "']").index();
	if (turn == -1 && index == 0) {
		urp.alert("已处于第一项！");
		return;
	}
	if (turn == 1 && index == option.length - 1) {
		urp.alert("已处于最后一项！");
		return;
	}
	$("#" + xnxqId).val($("#" + xnxqId + " option:eq(" + (index + turn) + ")").val());
	$("#" + xnxqId).trigger("chosen:updated");
	$("#" + xnxqId).trigger("change");
//	$("#" + searchId).click();
}

urp = new Urp();

function Base64() {
	// private property
	_keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

	// public method for encoding
	this.encode = function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
		input = _utf8_encode(input);
		while (i < input.length) {
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
			output = output +
				_keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
				_keyStr.charAt(enc3) + _keyStr.charAt(enc4);
		}
		return output;
	};

	// public method for decoding
	this.decode = function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;
		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
		while (i < input.length) {
			enc1 = _keyStr.indexOf(input.charAt(i++));
			enc2 = _keyStr.indexOf(input.charAt(i++));
			enc3 = _keyStr.indexOf(input.charAt(i++));
			enc4 = _keyStr.indexOf(input.charAt(i++));
			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;
			output = output + String.fromCharCode(chr1);
			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}
		}
		output = _utf8_decode(output);
		return output;
	};

	// private method for UTF-8 encoding
	_utf8_encode = function (string) {
		string = string.replace(/\r\n/g, "\n");
		var utftext = "";
		for (var n = 0; n < string.length; n++) {
			var c = string.charCodeAt(n);
			if (c < 128) {
				utftext += String.fromCharCode(c);
			} else if ((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			} else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}
		return utftext;
	};

	// private method for UTF-8 decoding
	_utf8_decode = function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
		while (i < utftext.length) {
			c = utftext.charCodeAt(i);
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			} else if ((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i + 1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			} else {
				c2 = utftext.charCodeAt(i + 1);
				c3 = utftext.charCodeAt(i + 2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
		}
		return string;
	};
}